package com.cqw.auth.service;

import com.cqw.constant.Constants;
import com.cqw.domain.SysUser;
import com.cqw.utils.IdUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-16 17:10
 * @Description:
 */
@Component
public class TokenService {


    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取用户身份信息
     *
     * @param request
     * @return
     */
    public SysUser getLoginUser(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isNotBlank(token)) {
            Claims claims = parseToken(token);
            //解析对应的权限及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String key = getTokenKey(uuid);
            SysUser sysUser = (SysUser) redisTemplate.opsForValue().get(key);
            return sysUser;
        }
        return null;
    }


    /**
     * 从令牌中获取数据声明
     *
     * @param token
     * @return
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


    /**
     * 获取请求token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(this.header);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replaceAll(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }


    /**
     * 创建令牌
     *
     * @param loginUser 登录用户
     * @return 令牌
     */
    public Map<String, String> createToken(SysUser loginUser) {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        //设置用户

        //刷新token
        refreshToken(token, loginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        Map<String, String> map = new HashMap<>();
        map.put("uuid", token);
        map.put("token", createToken(claims));
        return map;
    }

    /**
     * 从数据声明生成token
     *
     * @param claims
     * @return
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    private void refreshToken(String uuid, SysUser loginUser) {
        String key = getTokenKey(uuid);
        redisTemplate.opsForValue().set(key, loginUser, expireTime, TimeUnit.MINUTES);
    }

    public String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }


    /**
     * 删除用户身份信息
     *
     * @param token
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotBlank(token)) {
            String tokenKey = getTokenKey(token);
            redisTemplate.delete(tokenKey);
        }
    }
}
